<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/16 0016
 * Time: 15:11
 */

namespace Admin\Controller;

class PowerController extends AuthController{

    public function index(){
        $group = M('auth_group');
        $groups = $group->select();
        $this->assign('group',$groups);
        $this->display('power');
    }

    public function add(){
        if(IS_POST){
            //dump(I('post.')) ;exit;
            $rules = I('post.');
            $rules['rules'] = implode(',' , $rules['rules']);
            //dump($rules);exit;
            $users = D('auth_group');
            if($users->create()){
                if($users->add($rules)){
                    $this->success('添加成功',U('power/index'));
                }else{
                    $this->error('添加失败');
                }
            }else{
                $this->error($users->getError());
            }
        }
        $auth = M('auth_rule')->select();
        $this->assign('auths' , $auth);
        $this->display('addpower');
    }

    public function editpower($id){
        $auth = D('auth_group');
        if(IS_POST){
            $post = I('post.');
            $post['rules'] = implode(',' , $post['rules']);
            //dump($post);exit;
            if($auth->create()){
                if($auth->save($post)){
                    $this->success('编辑成功',U('power/index'));
                }else{
                    $this->error('编辑失败');
                }
            }else{
                $this->error($auth->getError());
            }
        }
        $group = M('auth_group')->where('id='.$id)->find();
        $this->assign('auths' , $this->authlist(explode(',',$group['rules'])));
        $this->assign('group' , $group);
        $this->display('editpower');
    }

    public function delpower($id){
        $auth = M('auth_group');
        $re = $auth->delete($id);
        if($re){
			if(M('auth_group_access')->where('group_id="'.$id.'"')->save(array('group_id',2))){
				$this->success('删除成功！' , U('power/index'));
			}
        }else{
            $this->error('删除失败');
        }
    }

    public function authlist($array = array()){
        $list = D('auth_rule')->select();
        $temp = '';
        foreach($list as $key=>$val){
            $chked = '';
            if(in_array($val['id'] , $array)){
                $chked = 'checked="checked"';
            }
            $html = '';
            $html .= '<span style="display:inline-block;width:100px;line-height:30px;"><input type="checkbox" name="rules[]" value="' . $val['id'] . '" '.$chked.'/>' . $val['title'] . '</span>';
            $temp .= $html;
        }
        return $temp;
    }

}
